package cn.hongwei.config;

import cn.hongwei.pojo.User;
import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.annotations.Mapper;
import org.aspectj.lang.annotation.Aspect;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @author Great
 * @email 1224028994@qq.com
 */
@EnableTransactionManagement
@ComponentScan("cn.hongwei")
@PropertySource("dbConfig.properties")
//@MapperScan("cn.hongwei.dao")
@Configuration //在有事务的时候必须加这个注解,要不然事务不生效
public class MybatisSpringConfig {


//    @Bean(initMethod = "init",destroyMethod = "close")
    @Bean
    public DataSource dataSource(){
        DruidDataSource dataSource=new DruidDataSource();
        dataSource.setUsername("root");
        dataSource.setPassword("Shw@root");
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://localhost:3306/mydb3?useSSL=false");
        return dataSource;
    }


    //配置mybatis核心工厂
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(){
        SqlSessionFactoryBean sqlSessionFactory=new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource());
        //ClassPathResource resource=new ClassPathResource("mybatis-config.xml");
        ClassPathResource resource=new ClassPathResource("cn/hongwei/dao/IUserDao.xml");
        //sqlSessionFactory.setConfigLocation(resource);
        //设置别名,已经在mybatis的主配置文件设置过了
        sqlSessionFactory.setTypeAliasesPackage("cn.hongwei.pojo");
        sqlSessionFactory.setMapperLocations(new ClassPathResource[]{resource});
        return sqlSessionFactory;
    }

    //配置了这个就不用写@MapperScan注解了
    @Bean
    public MapperScannerConfigurer  mapperScannerConfigurer(){
        MapperScannerConfigurer configurer=new MapperScannerConfigurer();
        configurer.setBasePackage("cn.hongwei.dao");
        return configurer;
    }

    //配置事务
    @Bean
    public PlatformTransactionManager transactionManager(){
        DataSourceTransactionManager transactionManager=new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource());
        return transactionManager;
    }

}
